package com.example.system.handler;

import cn.hutool.json.JSONUtil;
import com.example.commons.core.domain.BaseResponse;
import com.example.commons.core.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 异常处理类
 */
@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理运行异常
     */
    @ExceptionHandler({ServiceException.class, IllegalArgumentException.class, RuntimeException.class})
    public BaseResponse<Object> handleRuntimeException(HttpServletRequest request, RuntimeException ex) {
        log.error("", ex);
        log.error("请求地址：" + request.getRequestURL());
        log.error("请求参数: " + JSONUtil.toJsonStr(request.getParameterMap()));
        return BaseResponse.fail(ex.getMessage());
    }

    /**
     * 用来捕获404，400这种无法到达controller的错误
     *
     * @param ex
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public BaseResponse<Object> defaultErrorHandler(Exception ex) throws Exception {
        log.error("", ex);
        BaseResponse<Object> result = BaseResponse.fail(ex.getMessage());
        if (ex instanceof NoHandlerFoundException) {
            result.setCode(404);
        } else {
            result.setCode(500);
        }
        result.setData(null);

        return result;
    }
}
